package com.zcn.io.web.config;

import com.zcn.io.common.exception.ServiceException;
import com.zcn.io.common.pojo.CommonResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.rmi.AccessException;
import java.util.List;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public CommonResult<String> exceptionHandler(HttpServletRequest request, Exception e){
        //绑定异常是需要明确提示给用户的
        if(e instanceof ServiceException){
            ServiceException exception=(ServiceException) e;
            return CommonResult.error(exception.getCode(), exception.getMessage());
        }
        // 登录异常
        if (e instanceof BadCredentialsException) {
            return CommonResult.error(401, e.getMessage());
        }

        if (e instanceof AccessDeniedException) {
            return CommonResult.error(403, "权限不足");
        }
        e.printStackTrace();
        return CommonResult.error(500, e.getMessage());
    }
}
